<?php
namespace app\web\controller;

use app\model\Theme; 
use app\model\Poster; 
use app\model\Order; 

class Bill extends Base
{
    public function Bill()
    {
global $_G, $_P;
$system = $_G['system'];
$_G['page']['title'] = '提现/充值 - ' . $system['sysname'];
//load_func('tpl');
$GLOBALS['frames'] = array();
$themeid = intval($_P['themeid']);
if($themeid <= 0){
	$themeid = Theme::getDefaultThemenew();
}
$theme = Theme::getThemeById($themeid);
if(empty($theme['id'])){
	return_msg('还没有创建活动,请联系管理员');
}
if(empty($theme['softsn'])){
    return_msg('软件未激活,无法使用');
}

$config = 	Theme::getConfig($themeid);
$id = $_P['id'];
$do = 'theme';
$op = !empty($_P['op']) ? $_P['op'] : 'display';
if (!$_G['isSuperAdmin'] && ($op =='topup' || $op =='withdraw') ){
	return_msg('没有权限操作');
}

if($op !== 'display' && $op !== 'view') {
	if (!empty($system['tiaozhuanurl'])) {
		if (stripos($system['tiaozhuanurl'],'跳转至')!==false) {
			return_msg("此链接已失效，所有活动已".$system['tiaozhuanurl']);
		}else{
			return_msg("此活动已设置跳转至".$system['tiaozhuanurl'] );
		}	
	}
}

$shouxu2 = Order::shouxufei();
$shouxu100 = Order::shouxufei()*100;

$url = createWebUrl('bill',array('op' => 'display','themeid'=>$themeid));

if($op == 'display') {
	$sql = "SELECT * FROM " . tablename ( t_bill ) . " 
				WHERE software = '" . MODULE_NAME . "' and  themeid ='{$themeid}' and (type=0 or type =1) ORDER BY addtime asc ";
	$list = db_select ( $sql);
}
if($op == 'view') {
	$sql = "SELECT * FROM " . tablename ( t_bill ) . " 
				WHERE software = '" . MODULE_NAME . "' and  themeid ='{$themeid}' and (type=0 or type =1) and id ='{$id}'";
	$bill = db_find ( $sql);
	if (empty($bill)) {
		return_msg('没有找到此记录');
	}
}

if($op == 'zhuanzhang') {
	$sql = "SELECT * FROM " . tablename ( t_bill ) . " 
				WHERE software = '" . MODULE_NAME . "' and  themeid ='{$themeid}' and id ='{$id}'";
	$bill = db_find ( $sql);
	if (empty($bill)) {
		return_msg('没有找到此记录');
	}

	if ($bill['status'] > 1) {
		return_msg('此单已转帐');
	}
	$result = Poster::Getbanklist($system,'getbank','');
	$banklist = $result['banklist'];
	$paymentlist = $result['payment'];
	// $personnel = $result['personnel'];
	if (empty($banklist[0]['bankname']) || empty($paymentlist[0]['name'])) {
		return_msg('读取公司帐户信息失败！');
	}

	if(checksubmit('submit')) {
		if ($_G['username']=='chuna') {
			$paytime = strtotime(($_P['paytime']));
			if ($paytime < strtotime("-3 day")){
				return_msg('交易时间必须为3天之内');
			}
			if (empty($_P['yxaccount'])){
				return_msg('公司帐户必须选择');
			}
			$userrecord = $bill['userrecord'] . date('m-d H:i') . ' 转帐：'.$_G['username'].' ' . $_G['clientip'] . '<br>';
			$data = array(
				'status'	=>	2,
				'yxaccount'     => $_P['yxaccount'],
				'payment'     => $_P['payment'],
				'imgs'     => tomedia($_P['imgs']), //serialize()和unserialize()方式
				'paytime'       => $paytime,
				'notes'     => htmlspecialchars_decode($_P['notes']),
				'userrecord' => $userrecord,
				'serverid' => $bill['serverid'],
			);	
			$banklist = Poster::Getbanklist($system,'savebankzz',$data);
			if (empty($banklist['msg'])) {
				return_msg('保存数据失败！');
			}
			if ($banklist['error']>0) {
				return_msg($banklist['msg']);
			}
			db_update(t_bill, $data,array('id' => $id));
			return_msg('保存成功',$url,success);
		}else{
			return_msg('无权操作');
		}
	}
}
if($op == 'shenhe') {
	$sql = "SELECT * FROM " . tablename ( t_bill ) . " 
				WHERE software = '" . MODULE_NAME . "' and  themeid ='{$themeid}' and id ='{$id}'";
	$bill = db_find ( $sql);
	if (empty($bill)) {
		return_msg('没有找到此记录');
	}
	if ($bill['status'] > 0) {
		return_msg('此单已审核');
	}
	if(checksubmit('submit')) {
		if ($_G['username']=='caiwu') {
			$userrecord = $bill['userrecord'] . date('m-d H:i') . ' 帐单审核：'.$_G['username'].' ' . $_G['clientip'] . '<br>';
			$data = array(
				'status'	=>	1,
				'userrecord' => $userrecord,
				'notes'     => htmlspecialchars_decode($_P['notes']),
				'serverid' => $bill['serverid'],
			);	
			$banklist = Poster::Getbanklist($system,'savebanksh',$data);
			if (empty($banklist['msg'])) {
				return_msg('保存数据失败！');
			}
			if ($banklist['error']>0) {
				return_msg($banklist['msg']);
			}
			db_run('set AUTOCOMMIT=0');//关闭自动提交，自此句执行以后，每个SQL语句或者语句块所在的事务都需要显示"commit"才能提交事务
			db_run('START TRANSACTION');//启动一个新事务
			$billstate = db_update(t_bill, $data,array('id' => $id));
			$p = array(":themeid"=>$themeid);
			$themestate = db_query("UPDATE ".tablename(t_theme)." SET chongzhi = chongzhi - ". $bill['withdraw'] ." WHERE id =:themeid",$p); 
			if (!$billstate || !$themestate) {
				db_run('ROLLBACK');//事务回滚
				return_msg('操作失败',$url,error);
			}else{
				db_run('COMMIT');//事务提交
				return_msg('审核通过',$url,success);
			}

		}else{
			return_msg('无权操作');
		}
	}
}


if($op == 'zhuanzhangcz') {
	$sql = "SELECT * FROM " . tablename ( t_bill ) . " 
				WHERE software = '" . MODULE_NAME . "' and  themeid ='{$themeid}' and id ='{$id}'";
	$bill = db_find ( $sql);
	if (empty($bill)) {
		return_msg('没有找到此记录');
	}

	if ($bill['status'] > 1) {
		return_msg('此单已充值审核');
	}

	$bill['paytime'] = TIMESTAMP;
	$result = Poster::Getbanklist($system,'getbank','');
	$banklist = $result['banklist'];
	$paymentlist = $result['paymenttopup'];


	if (empty($banklist[0]['bankname']) || empty($paymentlist[0]['name'])) {
		return_msg('读取公司帐户信息失败！');
	}

	if(checksubmit('submit')) {
		if (empty($_P['yxaccount'])){
			return_msg('公司帐户必须选择');
		}
		$paytime = strtotime(($_P['paytime']));
		if ($paytime < strtotime("-3 day")){
			return_msg('交易时间必须为3天之内');
		}
		if ($_G['username']=='caiwu' || $_G['username']=='chuna') {
			$userrecord = $bill['userrecord'] . date('m-d H:i') . ' 转帐：'.$_G['username'].' ' . $_G['clientip'] . '<br>';

			$data = array(
				'status'	=>	2,
				'yxaccount'     => $_P['yxaccount'],
				'payment'     => trim($_P['payment']),
				'imgs'     => tomedia($_P['imgs']), //serialize()和unserialize()方式
				'paytime'       => $paytime,
				'notes'     => htmlspecialchars_decode($_P['notes']),
				'userrecord' => $userrecord,
				'serverid' => $bill['serverid'],
			);

			$banklist = Poster::Getbanklist($system,'savebankzz',$data);
			if (empty($banklist['msg'])) {
				return_msg('保存数据失败！');
			}
			if ($banklist['error']>0) {
				return_msg($banklist['msg']);
			}
			db_update(t_bill, $data,array('id' => $id));
			return_msg('充值审核通过',$url,success);
		}else{
			return_msg('无权操作');
		}
	}
}

if($op == 'topup'){
	if (empty($id)) {
		$bill['paytime'] = TIMESTAMP;
	}
	
	$result = Poster::Getbanklist($system,'getbank','');
	$banklist = $result['banklist'];
	$paymentlist = $result['paymenttopup'];
	$personnel = $result['personnel'];
	if (empty($banklist[0]['bankname']) || empty($paymentlist[0]['name'])) {
		return_msg('读取公司帐户信息失败！');
	}
	if(checksubmit('submit')) {
		$imgs = $_P['imgs'];
		// if(empty($imgs)){
		// 	return_msg('交易凭证图不可为空');
		// }
		$paytime = strtotime(($_P['paytime']));
		if ($paytime < strtotime("-3 day")){
			return_msg('交易时间必须为3天之内');
		}
		$data = array(
			'software'    => MODULE_NAME,
            'uniacid'  => $_G['mpid'],
			'themeid' => $themeid,
			'type' => 1,
			'topup'       => floatval($_P['topup']),
			// 'yxaccount'     => $_P['yxaccount'],
			'payment'     => $_P['payment'],
			// 'personnel'     => $_P['personnel'],
			'imgs'     => tomedia($_P['imgs']), //serialize()和unserialize()方式
			'paytime'       => $paytime ,
			'notes'     => htmlspecialchars_decode($_P['notes']),
			'ip' => $_G['clientip'],
			'user' => $_G['username'],
			'addtime' => TIMESTAMP,
		);	
		$banklist = Poster::Getbanklist($system,'savebank',$data);
		if (empty($banklist['msg'])) {
			return_msg('保存数据失败！');
		}
		if ($banklist['error']>0) {
			return_msg($banklist['msg']);
		}
		$data['serverid'] = $banklist['id'];
		$data['personnel'] = $banklist['personnel'];

		db_run('set AUTOCOMMIT=0');//关闭自动提交，自此句执行以后，每个SQL语句或者语句块所在的事务都需要显示"commit"才能提交事务
		db_run('START TRANSACTION');//启动一个新事务
		$billstate = $insertid = db_insert(t_bill, $data);
		$p = array(":themeid"=>$themeid);
		$themestate = db_query("UPDATE ".tablename(t_theme)." SET chongzhi = chongzhi + ". floatval($_P['topup']) ." WHERE id =:themeid",$p); 
		if (!$billstate || !$themestate) {
			db_run('ROLLBACK');//事务回滚
			return_msg('操作失败',$url,error);
		}else{
			db_run('COMMIT');//事务提交
       		return_tips('充值审请已提交,待审核',$url, 'success');
		}

	}
}

if($op == 'edit'){
	if ($_G['username']=='caiwu' || $_G['username']=='chuna') {
		return_msg('无权操作！');
	}
	$data = array(
		'software'    => MODULE_NAME,
        'uniacid'  => $_G['mpid'],
		'themeid' => $themeid,
	);
	$result = Poster::Getbanklist($system,'getbank',$data);

	$sql = "SELECT * FROM " . tablename ( t_bill ) . " 
				WHERE software = '" . MODULE_NAME . "' and  themeid ='{$themeid}' and id ='{$id}'";
	$bill = db_find ( $sql);
	if (empty($bill)) {
		return_msg('没有找到此记录');
	}

	if(checksubmit('submit')) {
		if ($_G['isSuperAdmin'] && $_G['username']!=='caiwu' && $_G['username']!=='chuna'){ 
			$imgs = $_P['imgs'];
			// if(empty($imgs)){
			// 	return_msg('交易凭证图不可为空');
			// }
			$paytime = strtotime(($_P['paytime']));

			$feehz = floatval(db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
					WHERE  themeid = '{$themeid}' and paystate = 1 and realfee > 0 " ));
			$billsxf = sprintf("%.2f", $feehz*$shouxu2) ;
			$commcount = floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
	            WHERE  themeid ='{$themeid}'  and status  = 1 " ));
			//echo $feehz .'-'. $billsxf .'-'.$commcount .'-'.$theme['chongzhi'];
			//exit;
			$billtixian = sprintf("%.2f", $feehz - $billsxf -$commcount +$theme['chongzhi']);
			if ($_P['withdraw'] > $billtixian){
				return_msg('最多可提'.$billtixian.'元');
			}
			if ($_P['withdraw']<=0) {
				return_msg('提现金额必须为正数');
			}
			if (empty($_P['shopaccount'])) {
				return_msg('商家帐户不可为空');
			}

			$userrecord = date('m-d H:i') . ' 修改审请：'.$_G['username'].' ' . $_G['clientip'] . '<br>';
			if (empty($result['wechat1']) && empty($result['wechat2']) && empty($result['openid']) && empty($result['bankid'])) {
				$shopaccount = "手工输入:".$_P['shopaccount'];
			}else{
				$shopaccount = $_P['shopaccount'];
			}

			$data = array(
				'software'    => MODULE_NAME,
	            'uniacid'  => $_G['mpid'],
				'themeid' => $themeid,
				'type' => 0,
				'bill'     => $_P['bill'],
				'withdraw'       => floatval($_P['withdraw']),
				'shopaccount'     => $shopaccount,
				'notes'     => htmlspecialchars_decode($_P['notes']),
				'status'	=>	0,
				'ip' => $_G['clientip'],
				'user' => $_G['username'],
				'addtime' => TIMESTAMP,
				'userrecord' => $userrecord,
			);

			$userrecord = $bill['userrecord'] . date('m-d H:i') . ' 帐单审核：'.$_G['username'].' ' . $_G['clientip'] . '<br>';
			$data['serverid'] = $bill['serverid'];

			$banklist = Poster::Getbanklist($system,'editbank',$data);
			if (empty($banklist['msg'])) {
				return_msg('保存数据失败！');
			}
			if ($banklist['error']>0) {
				return_msg($banklist['msg']);
			}
			db_update(t_bill, $data,array('id' => $id));
	        return_tips('提现审请修改成功,待审核',$url, 'success');
	    }
	}
}
if($op == 'withdraw'){

	if ($_G['username']=='caiwu' || $_G['username']=='chuna') {
		return_msg('无权操作！');
	}

	$sql = "SELECT * FROM " . tablename ( t_bill ) . " 
				WHERE status=0 and software = '" . MODULE_NAME . "' and  themeid ='{$themeid}'";
	$bill = db_find ( $sql);
	if (!empty($bill)) {
		return_msg('此活动还有未完成的提现,不可再有新的提现,请联系财务完成上一个提现,或修改你现有的提现');
	}

	$data = array(
		'software'    => MODULE_NAME,
        'uniacid'  => $_G['mpid'],
		'themeid' => $themeid,
	);
	$result = Poster::Getbanklist($system,'getbank',$data);

	if (empty($id)) {
		$bill['paytime'] = TIMESTAMP;

		$record = db_select("SELECT count(id) as danshu,fee FROM " . tablename ( t_record ) . "
				WHERE themeid = '{$themeid}' and status > 0  and status!=3 group by fee");
		$billvalue = "感谢您的信任与选择! 麻烦您核验一下提现金额: \n";
		$billvalue = $billvalue . "软件ID：" . MODULE_NAME ."\n";
			foreach ($record as $index => $item) {
				$feedg = $item['danshu'] * $item['fee'];
				$feehz = $feehz +$feedg;
				if (count($record)>1) {
					$indexn = $index +1;
				}
				$billvalue = $billvalue . "定单" . $indexn . "：" . $item['danshu'] . "个*" . $item['fee'] . "元=". $feedg ." 元\n";
			}
		if (count($record)>1) {
			$billvalue = $billvalue . "总收入：" . $feehz  . "元\n";
		}


		$billsxf = sprintf("%.2f", $feehz*$shouxu2) ;
		$billvalue = $billvalue . "手续费(微信扣".$shouxu100 ."%)：" . $billsxf . "元\n";
		
		$commcount = floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE  themeid ='{$themeid}'  and status  = 1 " ));
		if ($commcount>0) {
			$billvalue = $billvalue . "红包发放：" . $commcount . "元\n";
		}

		if ($theme['chongzhi']>0) {
			$billvalue = $billvalue . "充值：" . $theme['chongzhi'] . "元\n";
		}elseif ($theme['chongzhi']<0) {
			$billvalue = $billvalue . "已提现：" . -$theme['chongzhi'] . "元\n";
		}
		$billtixian = sprintf("%.2f", $feehz - $billsxf -$commcount +$theme['chongzhi']) ;
		$billvalue = $billvalue . "本次提现：" . $billtixian . "元\n";
		$billvalue = $billvalue . "财务 " . date("Y-m-d H:i:s");

		$bill['bill'] = $billvalue ;
		$bill['withdraw'] = $billtixian;
	}


	if(checksubmit('submit')) {
		if ($_G['isSuperAdmin'] && $_G['username']!=='caiwu' && $_G['username']!=='chuna'){ 
			$imgs = $_P['imgs'];
			// if(empty($imgs)){
			// 	return_msg('交易凭证图不可为空');
			// }
			$paytime = strtotime(($_P['paytime']));

			$feehz = floatval(db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
					WHERE  themeid = '{$themeid}' and paystate = 1 and realfee > 0 " ));
			$billsxf = sprintf("%.2f", $feehz*$shouxu2) ;
			$commcount = floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
	            WHERE  themeid ='{$themeid}'  and status  = 1 " ));
			//echo $feehz .'-'. $billsxf .'-'.$commcount .'-'.$theme['chongzhi'];
			//exit;
			$billtixian = sprintf("%.2f", $feehz - $billsxf -$commcount +$theme['chongzhi']);
			if ($_P['withdraw'] > $billtixian){
				return_msg('最多可提'.$billtixian.'元');
			}
			if ($_P['withdraw']<=0) {
				return_msg('提现金额必须为正数');
			}
			if (empty($_P['shopaccount'])) {
				return_msg('商家帐户不可为空');
			}

			$userrecord = date('m-d H:i') . ' 提现审请：'.$_G['username'].' ' . $_G['clientip'] . '<br>';
			if (empty($result['wechat1']) && empty($result['wechat2']) && empty($result['openid']) && empty($result['bankid'])) {
				$shopaccount = "手工输入:".$_P['shopaccount'];
			}else{
				$shopaccount = $_P['shopaccount'];
			}

			$data = array(
				'software'    => MODULE_NAME,
	            'uniacid'  => $_G['mpid'],
				'themeid' => $themeid,
				'type' => 0,
				'bill'     => $_P['bill'],
				'withdraw'       => floatval($_P['withdraw']),
				'shopaccount'     => $shopaccount,
				'notes'     => htmlspecialchars_decode($_P['notes']),
				'status'	=>	0,
				'ip' => $_G['clientip'],
				'user' => $_G['username'],
				'addtime' => TIMESTAMP,
				'userrecord' => $userrecord,
			);	
			$banklist = Poster::Getbanklist($system,'savebank',$data);
			if (empty($banklist['msg'])) {
				return_msg('保存数据失败！');
			}
			if ($banklist['error']>0) {
				return_msg($banklist['msg']);
			}
			$data['serverid'] = $banklist['id'];
			$data['personnel'] = $banklist['personnel'];
			$insertid = db_insert(t_bill, $data);
	        return_tips('提现审请成功,待审核',$url, 'success');
	    }
	}
}
$return_clicent = get_defined_vars();
return view('/bill' , $return_clicent);
}
}